package com.nero.controller;

import com.alibaba.fastjson.JSONObject;
import com.nero.common.pojo.UpLoadFileResult;

import com.nero.common.utils.ResponseUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by Nero on 18/8/7.
 */
@RequestMapping("/pic")
@Controller
public class ImageController {


    private static Logger logger = LogManager.getLogger(ImageController.class);

    @RequestMapping("/upload")
    @ResponseBody
    public UpLoadFileResult upload(@RequestParam(value = "uploadFile", required = false) MultipartFile uploadFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("开始上传图片");
        UpLoadFileResult result = new UpLoadFileResult();
        // 图片名称生成策略---采用时间格式(精确到毫秒)并追加3位(10以内)数字
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String picName = df.format(new Date());
        // 随机再生成3位 10以内的数
        Random r = new Random();
        for (int i = 0; i < 3; i++) {
            picName += r.nextInt(10);
        }
        // 获取扩展名
        String originalFilname = uploadFile.getOriginalFilename();
        String ext = FilenameUtils.getExtension(originalFilname);
        String path = "upload/" + picName + "." + ext;
        // 全路径，该路径为后面创建的tomcat图片服务器的上传图片的web工程下存放图片的路径
        String url = "http://172.16.16.87:8080/ImageWeb/" + path;
        // jersey 发送另一台Tomcat(可读写的)
        Client client = new Client();
        WebResource resource = client.resource(url);

        try {
            resource.put(String.class, uploadFile.getBytes());
            result.setError(0);
            result.setUrl(url);
            logger.info("上传图片成功");
        } catch (UniformInterfaceException | ClientHandlerException | IOException e1) {
            // TODO Auto-generated catch block
            result.setError(1);
            result.setMessage("上传图片失败..");
            e1.printStackTrace();
        }

//        JSONObject json = new JSONObject();
//        json.put("url", url);
//        json.put("path", path);
//        ResponseUtils.renderJson(response, json.toString());
        return result;
    }
}